package com.hs.mod_archive.fragment

import android.R
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import com.hs.framework.base.BaseDataBindFragment
import com.hs.framework.utils.MMKVUtil
import com.hs.mod_archive.Const.ACT_CONFIG_SERIAL_INTERFACE
import com.hs.mod_archive.databinding.FragmentDevOtherConfigBinding
import com.hs.serial.TtyUtils
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.IOException
import java.io.InputStreamReader

class FragmentDevOtherConfig : BaseDataBindFragment<FragmentDevOtherConfigBinding>() {


    override fun initView(view: View, savedInstanceState: Bundle?) {
        mBinding!!.reboot.setOnClickListener { reboot() }
        mBinding!!.restart.setOnClickListener { restart() }
        val ttys = TtyUtils.ttys
        val adapter = ArrayAdapter(
            requireActivity(), R.layout.simple_spinner_item, ttys
        )

        adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item)
        mBinding!!.lockInterface.adapter = adapter

        val adapter2 = ArrayAdapter(
            requireActivity(), R.layout.simple_spinner_item, TtyUtils.bRate
        )
        adapter2.setDropDownViewResource(R.layout.simple_spinner_dropdown_item)
        mBinding!!.lockBaudRate.adapter = adapter2
        val adapter3 = ArrayAdapter(
            requireActivity(), R.layout.simple_spinner_item, ttys
        )
        adapter3.setDropDownViewResource(R.layout.simple_spinner_dropdown_item)
        mBinding!!.readerInterface.adapter = adapter3

        val adapter4 = ArrayAdapter(
            requireActivity(), R.layout.simple_spinner_item, TtyUtils.bRate
        )
        adapter4.setDropDownViewResource(R.layout.simple_spinner_dropdown_item)
        mBinding!!.readerBaudRate.adapter = adapter4

        mBinding!!.lockInterface.setSelection(
            ttys.indexOf(
                MMKVUtil.getString(
                    TtyUtils.K_LOCK_PATH, ttys[0]
                )
            )
        )
        mBinding!!.lockBaudRate.setSelection(
            TtyUtils.bRate.indexOf(
                MMKVUtil.getInt(
                    TtyUtils.K_LOCK_RATE, TtyUtils.bRate[0]
                )
            )
        )
        mBinding!!.readerInterface.setSelection(
            ttys.indexOf(
                MMKVUtil.getString(
                    TtyUtils.K_READER_PATH, ttys[0]
                )
            )
        )
        mBinding!!.readerBaudRate.setSelection(
            TtyUtils.bRate.indexOf(
                MMKVUtil.getInt(
                    TtyUtils.K_READER_RATE, TtyUtils.bRate[0]
                )
            )
        )

        mBinding!!.config.setOnClickListener {
            MMKVUtil.putString(
                TtyUtils.K_LOCK_PATH, mBinding!!.lockInterface.selectedItem.toString()
            )
            MMKVUtil.putInt(
                TtyUtils.K_LOCK_RATE, TtyUtils.bRate[mBinding!!.lockBaudRate.selectedItemPosition]
            )
            MMKVUtil.putString(
                TtyUtils.K_READER_PATH, mBinding!!.readerInterface.selectedItem.toString()
            )
            MMKVUtil.putInt(
                TtyUtils.K_READER_RATE,
                TtyUtils.bRate[mBinding!!.readerBaudRate.selectedItemPosition]
            )
            val intent = Intent(ACT_CONFIG_SERIAL_INTERFACE)
            requireActivity().sendBroadcast(intent)
        }
    }


    override fun initData() {
        super.initData()
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding = null
    }


    private fun restart() {
        val intent =
            requireActivity().packageManager.getLaunchIntentForPackage(requireActivity().packageName)
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
        Runtime.getRuntime().exit(0)
    }

    private fun reboot(): String {
        var process: Process? = null
        var reader: BufferedReader? = null
        var inputStream: InputStreamReader? = null
        var os: DataOutputStream? = null
        try {
            process = Runtime.getRuntime().exec("su")
            inputStream = InputStreamReader(process.inputStream)
            reader = BufferedReader(inputStream)
            os = DataOutputStream(process.outputStream)
            os.writeBytes("reboot\n")
            os.writeBytes("exit\n")
            os.flush()
            var read: Int
            val buffer = CharArray(4096)
            val output = StringBuilder()
            while ((reader.read(buffer).also { read = it }) > 0) {
                output.append(buffer, 0, read)
            }
            process.waitFor()
            return output.toString()
        } catch (e: IOException) {
            throw RuntimeException(e)
        } catch (e: InterruptedException) {
            throw RuntimeException(e)
        } finally {
            try {
                os?.close()
                inputStream?.close()

                reader?.close()

                process?.destroy()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }
}
